package com.icongyou.enterprise.talent_analysis.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.icongyou.enterprise.talent_analysis.entity.AIInsightCache;
import com.icongyou.enterprise.talent_analysis.entity.StudentInsight;
import com.icongyou.enterprise.talent_analysis.mapper.AIInsightCacheMapper;
import com.icongyou.enterprise.talent_analysis.service.AIInsightCacheService;
import com.icongyou.enterprise.talent_analysis.service.AIInsightService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * AI洞察缓存服务实现
 * 使用数据库持久化缓存+异步生成策略
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AIInsightCacheServiceImpl implements AIInsightCacheService {
    
    private final AIInsightService aiInsightService;
    private final AIInsightCacheMapper cacheMapper;
    private final ObjectMapper objectMapper;
    
    // 缓存过期时间(小时)
    private static final int CACHE_EXPIRE_HOURS = 24;
    
    @Override
    public StudentInsight getFromCache(String studentId, String templateId) {
        try {
            AIInsightCache cache = cacheMapper.selectByStudentAndTemplate(studentId, templateId);
            
            if (cache == null) {
                return null;
            }
            
            // 反序列化JSON
            StudentInsight insight = objectMapper.readValue(cache.getInsightJson(), StudentInsight.class);
            return insight;
            
        } catch (Exception e) {
            return null;
        }
    }
    
    @Override
    public void putToCache(String studentId, String templateId, StudentInsight insight) {
        try {
            // 查询是否已存在
            AIInsightCache existing = cacheMapper.selectByStudentAndTemplate(studentId, templateId);
            
            String insightJson = objectMapper.writeValueAsString(insight);
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime expireAt = now.plusHours(CACHE_EXPIRE_HOURS);
            
            if (existing != null) {
                // 更新
                existing.setInsightJson(insightJson);
                existing.setUpdatedAt(now);
                existing.setExpireAt(expireAt);
                cacheMapper.updateByIdWithVersion(existing);
            } else {
                // 插入
                AIInsightCache cache = new AIInsightCache();
                cache.setId(UUID.randomUUID().toString());
                cache.setStudentId(studentId);
                cache.setTemplateId(templateId);
                cache.setInsightJson(insightJson);
                cache.setAiModelVersion(insight.getAiModelVersion());
                cache.setGeneratedAt(now);
                cache.setUpdatedAt(now);
                cache.setExpireAt(expireAt);
                cache.setVersion(0);
                cacheMapper.insert(cache);
            }
        } catch (Exception e) {
        }
    }
    
    @Override
    @Async("aiInsightTaskExecutor")
    public void asyncRegenerateInsight(String studentId, String templateId, String hrUserId) {
        
        try {
            // 生成新的AI洞察报告
            StudentInsight insight = aiInsightService.generateStudentInsight(studentId, hrUserId);
            
            // 更新缓存
            putToCache(studentId, templateId, insight);
            
        } catch (Exception e) {
        }
    }
    
    @Override
    @Async("aiInsightTaskExecutor")
    public void batchAsyncRegenerateInsights(
        List<String> studentIds, 
        String oldTemplateId, 
        String newTemplateId,
        String hrUserId
    ) {
        
        int successCount = 0;
        int failCount = 0;
        
        for (String studentId : studentIds) {
            try {
                // 1. 使旧模板缓存失效
                if (oldTemplateId != null) {
                    cacheMapper.deleteByTemplateId(oldTemplateId);
                }
                
                // 2. 生成新模板的AI洞察
                StudentInsight insight = aiInsightService.generateStudentInsight(studentId, hrUserId);
                
                // 3. 缓存新结果
                putToCache(studentId, newTemplateId, insight);
                
                successCount++;
                
                // 避免过快调用AI,适当延迟
                if (successCount % 10 == 0) {
                    Thread.sleep(1000);
                }
                
            } catch (Exception e) {
                failCount++;
            }
        }
        
    }
    
    @Override
    public void invalidateStudentCache(String studentId) {
        cacheMapper.deleteByStudentId(studentId);
    }
    
    @Override
    public void invalidateTemplateCache(String templateId) {
        cacheMapper.deleteByTemplateId(templateId);
    }
    
    @Override
    public boolean isCacheExpired(String studentId, String templateId) {
        AIInsightCache cache = cacheMapper.selectByStudentAndTemplate(studentId, templateId);
        return cache == null;  // 查询时已过滤过期记录
    }
}
